<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="数据稽查" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading" @add="handleAdd" @delete="handleBatchDelete" @refresh="getData" />
      </template>
      <NDataTable v-model:checked-row-keys="checkedRowKeys" :columns="columns" :data="dataSource" size="small"
        :flex-height="!appStore.isMobile" :scroll-x="1200" :loading="loading" remote :row-key="row => row.id"
        :pagination="mobilePagination" class="sm:h-full" />
      <CheckTaskOperateDrawer v-model:visible="drawerVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getData" />
      <CheckResultDrawer v-model:visible="resultVisible" :task-id="currentTaskId" />
    </NCard>
  </div>
</template>

<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchCheckTaskList, deleteCheckTask, executeCheckTask } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import CheckTaskOperateDrawer from './modules/check-task-operate-drawer.vue';
import CheckResultDrawer from './modules/check-result-drawer.vue';

const appStore = useAppStore();

const resultVisible = ref(false);
const currentTaskId = ref<number>(0);

const { columns, columnChecks, data, getData, loading, mobilePagination } = useTable({
  apiFn: fetchCheckTaskList,
  apiParams: {
    pageNum: 1,
    pageSize: 10
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: 'ID',
      align: 'center',
      width: 80
    },
    {
      key: 'name',
      title: '任务名称',
      align: 'center',
      minWidth: 150
    },
    {
      key: 'tableName',
      title: '目标表',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'ruleCount',
      title: '规则数量',
      align: 'center',
      width: 100
    },
    {
      key: 'scheduleType',
      title: '调度类型',
      align: 'center',
      width: 100,
      render: row => {
        const typeMap: Record<string, { label: string; type: string }> = {
          MANUAL: { label: '手动', type: 'default' },
          CRON: { label: '定时', type: 'info' }
        };
        const type = typeMap[row.scheduleType] || { label: row.scheduleType, type: 'default' };
        return <NTag type={type.type as any}>{type.label}</NTag>;
      }
    },
    {
      key: 'lastExecuteTime',
      title: '最后执行时间',
      align: 'center',
      width: 180
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 80,
      render: row => {
        return <NTag type={row.status === 1 ? 'success' : 'error'}>{row.status === 1 ? '启用' : '禁用'}</NTag>;
      }
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 200,
      fixed: 'right',
      render: row => {
        return (
          <NSpace justify={'center'}>
            <NButton size={'small'} type="primary" onClick={() => handleExecute(row.id)}>
              执行
            </NButton>
            <NButton size={'small'} onClick={() => handleViewResult(row.id)}>
              查看结果
            </NButton>
            <NButton size={'small'} type="info" onClick={() => handleEdit(row.id)}>
              编辑
            </NButton>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => '确认删除',
                trigger: () => (
                  <NButton size={'small'} type="error">
                    删除
                  </NButton>
                )
              }}
            </NPopconfirm>
          </NSpace>
        );
      }
    }
  ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, getData);

async function handleBatchDelete() {
  await deleteCheckTask(checkedRowKeys.value);
  onBatchDeleted();
}

async function handleDelete(id: number) {
  await deleteCheckTask([id]);
  onDeleted();
}

async function handleExecute(id: number) {
  try {
    await executeCheckTask(id);
    window.$message?.success('稽查任务已提交执行');
    getData();
  } catch (error) {
    window.$message?.error('执行失败');
  }
}

function handleViewResult(id: number) {
  currentTaskId.value = id;
  resultVisible.value = true;
}

const dataSource = data;
</script>

<style scoped></style>
